<?php

namespace app\common\logic;

use app\common\model\SystemRegion;
use app\common\basic\BaseLogic;
use app\common\exception\ApiException;
use app\common\utils\Arr;
use app\common\utils\Helper;
use Overtrue\Pinyin\Pinyin;

/**
 * 地区逻辑层
 */
class SystemRegionLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SystemRegion();
        $this->defaultSort = ['adcode' => 'asc', 'id' => 'asc'];
    }

    /**
     * 数据树形化
     * @param $where
     * @return array
     */
    public function tree($where = []): array
    {
        $query = $this->search($where);
        $level = request()->input('level', 0);
        if (request()->input('tree', 'false') === 'true') {
            $query->field('id, id as value, name, name as label, parent_id, IF(level = '.$level.', 1, 0) isLeaf');
        }
        if ($level > 0) {
            $query->where('level', '<=', $level);
        }
        $query->order('level asc, adcode asc');
        $data = $this->getAll($query);
        return Helper::makeTree($data);
    }
    
    public function getAllRegion($where = [])
    {
        $query = $this->search($where);
        $query->field('*, id as value, name as label');
        $data = $this->getAll($query);
        return $data;
    }
    
    
}